#!/usr/bin/env python
import logging
import signal
from os import path
from server import server
from client import client
from world import world
from constants import mud, db
import pants

def main():
    logging.basicConfig(filename=path.join("logs", "mud.log"), level=logging.DEBUG)
    logger = logging.getLogger(__name__)
    logger.info("Starting server")
    engine = pants.engine.instance()
    serv = server(client)
    world.server = serv
    world.engine = engine
    world.running = True
    signal.signal(signal.SIGINT, shutdown)
    signal.signal(signal.SIGQUIT, shutdown)
    logger.info("Creating listening port")
    serv.listen((mud.addr, mud.port))
    engine.loop(world.schedule)
    while world.running:
        engine.poll(0.02)
    shutdown()

def shutdown(*args, **kwargs):
    world.shutdown()
    world.engine.stop()

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        world.shutdown()
    